<?php

namespace Wechat\Controller;

class HospitalProductController extends CommonController {

    public function index() {
        if(!check_role($this->customer["customer_id"], "1,2,3,7,8,10,11,13")){
            $this->error("您没有访问权限！");
            exit();
        }
        $this->assign("access", check_role($this->customer["customer_id"], "1,2,3,7,8,10,11,13"));
//        $user = D("admin")->where(array('employee_id'=>$this->customer["customer_id"]))->find();
//        $this->assign("user",$user);
        $this->display("index");
    }

    public function hospitalList() {
        $list = D("Hospital")->select();
        echo json_encode($list);
    }

    public function hospital() {
        if(!check_role($this->customer["customer_id"], "1,2,3,7,8,10,11,13")){
            $this->error("您没有访问权限！");
            exit();
        }
        $this->assign("access", check_role($this->customer["customer_id"], "1,2,3,7,8,10,11,13"));
        $id = $_REQUEST["id"];
        $hospital = D("Hospital")->queryById($id);
        $this->assign("hospital",$hospital);
        $this->display("hospital");
    }

    public function operationList() {
        $id = I("post.hospitalId");

        $map["hospital_id"] = $id;
        $list = D("HospitalOperation")
            ->where($map)
            ->select();
        echo json_encode($list);
    }

    public function getHospitalProductList() {
        $id = I("post.hospitalOperationId");

        $hospitalOperation = D("HospitalOperation")->queryById($id);
        $productIdArr = explode(',', $hospitalOperation["product_list"]);

        $allProductList = D('HospitalProduct')->select();
        $list =array();
//        foreach ($allProductList as $product) {
//            if (in_array($product["hospital_product_id"], $productIdArr)){
//                array_push($list, $product);
//            }
//        }
        foreach ($productIdArr as $productId) {
            foreach ($allProductList as $product) {
                if ($product["hospital_product_id"] == $productId){
                    array_push($list, $product);
                }
            }
        }

        echo json_encode($list);

    }

    public function hospitalOrder() {
        if(!check_role($this->customer["customer_id"], "1,2,3,7,8,10,11,13")){
            $this->error("您没有访问权限！");
            exit();
        }
        $id = $_REQUEST["id"];
        if(!isNullOrEmpty($id)) {
            $hospitalOrder = D("HospitalOrder")->queryById($id);
            $hospitalOperation = D("HospitalOperation")->queryById($hospitalOrder["hospital_operation_id"]);
            $hospital = D("Hospital")->queryById($hospitalOperation["hospital_id"]);
            $updater = D("Admin")->where(array('employee_id'=>$hospitalOrder["update_id"]))->find();
            $creator = D("Admin")->where(array('employee_id'=>$hospitalOrder["employee_id"]))->find();
            $this->assign("hospitalOrder", $hospitalOrder);
            $this->assign("updater", $updater);
            $this->assign("creator", $creator);
            $this->assign("emptyOrder", "0");
        }else{
            $hospitalOperation = D("HospitalOperation")->queryById($_REQUEST["opid"]);
            $hospital = D("Hospital")->queryById($hospitalOperation["hospital_id"]);
            $this->assign("emptyOrder", "1");
        }

        $user = D("admin")->where(array('employee_id'=>$this->customer["customer_id"]))->find();
        $this->assign("user", $user);

        $this->assign("hospitalOperation", $hospitalOperation);
        $this->assign("hospital", $hospital);

        $deliver = D("admin")->where(array('employee_id'=>$hospitalOrder["delivery_id"]))->find();
        $this->assign("deliver",$deliver);

        $this->display("hospitalOrder");

    }

    public function saveOrder() {

        $hospitalOrderId = $_REQUEST["hospitalOrderId"];
        $hospitalOrder = D("HospitalOrder")->queryById($hospitalOrderId);
        if($hospitalOrder["status"] == 1){
            $data["msg"] = "订单已发货，无法修改。";
            echo json_encode($data);
            return;
        }
        $data["code"] = 200;

        $user = D("admin")->where(array('employee_id'=>$this->customer["customer_id"]))->find();

        if(isNullOrEmpty($hospitalOrder["status"])){
            $hospitalOrder["enterprise_code"] = $user["enterprise_code"];
            $hospitalOrder["hospital_operation_id"] = I("post.hospitalOperationId");
            $hospitalOrder["create_time"] = getCurrentDate();
            $hospitalOrder["employee_id"] = $user["employee_id"];
            }

        if(I("post.saveStatus") == 0) {
            $hospitalOrder["status"] = -1;
        }
        if(I("post.saveStatus") == -1 && isNullOrEmpty($hospitalOrder["status"])){
            $hospitalOrder["status"] = -2;
        }
        if(I("post.saveStatus") == 2) {
            $hospitalOrder["status"] = 1;
            $hospitalOrder["delivery_id"] = $user["employee_id"];
            $hospitalOrder["outstock_time"] = getCurrentDate();
        }

        $hospitalOperation = D("HospitalOperation")->queryById($hospitalOrder["hospital_operation_id"]);
        $hospital = D("Hospital")->queryById($hospitalOperation["hospital_id"]);

        $hospitalOrder["update_id"] = $user["employee_id"];
        $hospitalOrder["update_time"] = getCurrentDate();
        $hospitalOrder["product_list"] = I("post.productList");
        $hospitalOrder["number_list"] = I("post.numberList");
        $hospitalOrder["report_list"] = I("post.reportList");
        $hospitalOrder["number"] = I("post.number");
        $hospitalOrder["create_date"] = I("post.createDate");
        $hospitalOrder["op_date"] = I("post.opDate");
        if($hospital["has_subhospital"] == 1)
            $hospitalOrder["subhospital_name"] = I("post.subhospitalName");
        $hospitalOrder["doctor_name"] = I("post.doctorName");
        $hospitalOrder["patient_name"] = I("post.patientName");
        $hospitalOrder["note"] = I("post.note");


        if(isNullOrEmpty($hospitalOrderId)){
            $hospitalOrderId = D("HospitalOrder")->add($hospitalOrder);
            $hospitalOrder["hospital_order_id"] = $hospitalOrderId;
            $hospitalOrder["hospital_order_no"] = "HOTS".date('Ymd',time()) . sprintf("%03d", substr($hospitalOrderId, -3, 3));
        }
        D("HospitalOrder")->updateInfo($hospitalOrder);

//        $hospitalProduct = D("HospitalProduct")->queryById($hospitalOrder["hospital_operation_id"]);
//        $hospitalProduct["count"] += $hospitalOrder["number"];

        //推送信息


        if(I("post.saveStatus") != -1){
            $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/hospitalProduct/hospitalOrderList/?id=". $hospitalOrderId;
            $notifyData["first"] = "收到新的手术订单。医院：" . $hospital["hospital_name"];
            if($hospital["has_subhospital"] == 1)
                $notifyData["first"] .= "（" . $hospitalOrder["subhospital_name"] ."）";
            if(I("post.saveStatus") == 1) {
                $notifyData["first"] = "手术订单内容变更。医院：" . $hospital["hospital_name"];
            }

            $creator = D("admin")->where(array('employee_id'=>$hospitalOrder["employee_id"]))->find();
            $notifyData["keyword1"] = $hospitalOrder["patient_name"];
            $notifyData["keyword2"] = "医生：" . $hospitalOrder["doctor_name"] ."，手术日期 ".$hospitalOrder["op_date"];

            $notifyData["keyword3"] = $hospitalOrder["hospital_order_no"] ."，下单人：".$creator["admin_name"] ."，下单日期 ".$hospitalOrder["create_date"];
            $notifyData["keyword4"] = $hospitalOrder["update_time"];
            $notifyData["keyword5"] = "[" . $hospitalOperation["hospital_operation_name"]."] 共 ".$hospitalOrder["number"]." 件";
            $notifyData["remark"] = $hospitalOrder["note"];

            if(I("post.saveStatus") == 1) {
                $notifyData["remark"] = "订单内容变更，请注意。";
                if(!isNullOrEmpty($hospitalOrder["note"])) {
                    $notifyData["remark"] .= "订单备注：" . $hospitalOrder["note"];
                }
            }
            if(I("post.saveStatus") == 2) {
                $notifyData["first"] = "手术订单已出库。医院：" . $hospital["hospital_name"];
                $notifyData["keyword4"] = $hospitalOrder["outstock_time"] . "，出库人：".$user["admin_name"];
            }

//            $adminRoleArr = array("1","8","10");
//            $openidArray = getNotifyArr($adminRoleArr, $user["enterprise_code"]);
            $openidArray = getNotifyArrByName("createHospitalOrder", $user["enterprise_code"]);

            array_push($openidArray, $creator["openid"]);
            array_push($openidArray, $user["openid"]);
            $openidArray = array_unique($openidArray);

            $exceptionOpenIdArray = getNotifyArrByName("exception", $user["enterprise_code"]);
            foreach ($openidArray as $openid) {
                if (in_array($openid, $exceptionOpenIdArray)) {
                    continue;
                }
                $notifyData["openid"] = $openid;
                hospitalOrderNotify($notifyData);
            }
        }

        $data["code"] = 200;
        echo json_encode($data);
    }

    public function hospitalOrderList() {
        if(!check_role($this->customer["customer_id"], "1,2,3,7,8,10,11,13")){
            $this->error("您没有访问权限！");
            exit();
        }
        $id = $_REQUEST["id"];
        $orderStatus = $_REQUEST["status"];
        $user = D("admin")->where(array('employee_id'=>$this->customer["customer_id"]))->find();
        $allProductList = D('HospitalProduct')->select();
        $this->assign("user", $user);
        $this->assign("orderId", $id);
        $this->assign("orderStatus", $orderStatus);
        $this->assign("allProductList", $allProductList);
        $this->display("hospitalOrderList");
    }

    public function getOrderList() {
//        $map["fo.status"] = array('neq','-3');
        $status = I("post.status");
        if(!isNullOrEmpty($status)) {
            $map["ho.status"] = $status;
        }
        if(!check_role($this->customer["customer_id"], "0,1,3,7,8,10,11,13")){
            $map["ho.employee_id"] = $this->customer["customer_id"];
        }
        $orderId = I("post.orderId");
        if(!isNullOrEmpty($orderId) && I("post.ignoreOrderId") != '1') {
            $map["hospital_order_id"] = $orderId;
        }
        $employee = D("admin")->where(array('employee_id'=>$this->customer["customer_id"]))->find();
        $map["ho.enterprise_code"] = $employee["enterprise_code"];
        $list = D("HospitalOrder")->alias("ho")
            ->join("left join __HOSPITAL_OPERATION__ hop on hop.hospital_operation_id = ho.hospital_operation_id")
            ->join("left join __HOSPITAL__ h on h.hospital_id = hop.hospital_id")
            ->join("left join __ADMIN__ e on e.employee_id = ho.employee_id")
            ->join("left join __ADMIN__ ad on ad.employee_id = ho.delivery_id")
            ->where($map)
            ->order("ho.hospital_order_id desc")
            ->field("ho.*,hop.hospital_operation_name, h.hospital_name, e.admin_name, ad.admin_name as delivery_name")
            ->select();

        echo json_encode($list);
    }
}